﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Prism.Core.Net.Tcp
{
    public class ConnectionListener
    {
        public event EventHandler<ConnectionCatchedEventArgs> ConnectionCatched;

        public ConnectionHost Host
        {
            get;
            set;
        }

        //private System.Threading.Thread Thread;
        private System.Timers.Timer Timer;
        protected TcpListener TcpListener;

        public ConnectionListener(ConnectionHost host)
        {
            this.Host = host;
            this.TcpListener = new TcpListener(this.Host.IPEndPoint);
            this.Timer = new System.Timers.Timer(1000d);
            this.Timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
            //this.Thread = new System.Threading.Thread(this.OnThreadStart);
            //this.Thread.IsBackground = true;

        }

        void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (this.TcpListener.Pending())
            {
                this.TcpListener.BeginAcceptTcpClient(this.OnTcpClientAccepted, null);
            }
        }

        public void Start()
        {
            this.TcpListener.Start();
            //this.Thread.Start();
            this.Timer.Start();
        }

        public void Stop()
        {
            this.Timer.Stop();
            //this.Thread.Abort();
            this.TcpListener.Stop();

        }

        protected void OnThreadStart()
        {
            while (true)
            {
                if (this.TcpListener.Pending())
                {
                    this.TcpListener.BeginAcceptTcpClient(this.OnTcpClientAccepted, null);
                }
            }
        }

        protected virtual void OnTcpClientAccepted(IAsyncResult ar)
        {
            if (ar.IsCompleted)
            {
                var connection = new Connection(this.TcpListener.EndAcceptTcpClient(ar));
                this.OnConnectionCatched(new ConnectionCatchedEventArgs() { Connection = connection });
            }
        }

        protected void OnConnectionCatched(ConnectionCatchedEventArgs e)
        {
            if (this.ConnectionCatched != null) { this.ConnectionCatched(this, e); }
        }

        ~ConnectionListener()
        {
            this.TcpListener.Stop();
        }
    }
}
